﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project1
{
    // 实体类定义
    #region 实体类
    public class School
    {
        public int SchoolId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }

        public override string ToString()
        {
            return $"学校ID: {SchoolId}, 名称: {Name}, 地址: {Address}";
        }
    }

    public class Class
    {
        public int ClassId { get; set; }
        public string Name { get; set; }
        public int SchoolId { get; set; }

        public override string ToString()
        {
            return $"班级ID: {ClassId}, 名称: {Name}, 学校ID: {SchoolId}";
        }
    }

    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public DateTime BirthDate { get; set; }
        public int ClassId { get; set; }

        public override string ToString()
        {
            return $"学生ID: {StudentId}, 姓名: {Name}, 性别: {Gender}, 出生日期: {BirthDate.ToShortDateString()}, 班级ID: {ClassId}";
        }
    }

    public class Log
    {
        public int LogId { get; set; }
        public DateTime Timestamp { get; set; }
        public string Operation { get; set; }
        public string Details { get; set; }

        public override string ToString()
        {
            return $"日志ID: {LogId}, 时间: {Timestamp}, 操作: {Operation}, 详情: {Details}";
        }
    }
    #endregion

    // 数据库管理类
    public class DatabaseManager
    {
        private readonly string _connectionString;
        private readonly string _dbPath = "StudentManagement.db";

        public DatabaseManager()
        {
            _connectionString = $"Data Source={_dbPath};Version=3;";
            InitializeDatabase();
        }

        private void InitializeDatabase()
        {
            if (!File.Exists(_dbPath))
            {
                SQLiteConnection.CreateFile(_dbPath);
            }

            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();

                // 创建学校表
                ExecuteNonQuery(connection, @"
                    CREATE TABLE IF NOT EXISTS Schools (
                        SchoolId INTEGER PRIMARY KEY AUTOINCREMENT,
                        Name TEXT NOT NULL,
                        Address TEXT
                    )");

                // 创建班级表
                ExecuteNonQuery(connection, @"
                    CREATE TABLE IF NOT EXISTS Classes (
                        ClassId INTEGER PRIMARY KEY AUTOINCREMENT,
                        Name TEXT NOT NULL,
                        SchoolId INTEGER,
                        FOREIGN KEY(SchoolId) REFERENCES Schools(SchoolId)
                    )");

                // 创建学生表
                ExecuteNonQuery(connection, @"
                    CREATE TABLE IF NOT EXISTS Students (
                        StudentId INTEGER PRIMARY KEY AUTOINCREMENT,
                        Name TEXT NOT NULL,
                        Gender TEXT,
                        BirthDate TEXT,
                        ClassId INTEGER,
                        FOREIGN KEY(ClassId) REFERENCES Classes(ClassId)
                    )");

                // 创建日志表
                ExecuteNonQuery(connection, @"
                    CREATE TABLE IF NOT EXISTS Logs (
                        LogId INTEGER PRIMARY KEY AUTOINCREMENT,
                        Timestamp TEXT NOT NULL,
                        Operation TEXT NOT NULL,
                        Details TEXT
                    )");
            }
        }

        private void ExecuteNonQuery(SQLiteConnection connection, string sql)
        {
            using (var command = new SQLiteCommand(sql, connection))
            {
                command.ExecuteNonQuery();
            }
        }

        public void LogOperation(string operation, string details)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    INSERT INTO Logs (Timestamp, Operation, Details)
                    VALUES (@Timestamp, @Operation, @Details)", connection))
                {
                    command.Parameters.AddWithValue("@Timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    command.Parameters.AddWithValue("@Operation", operation);
                    command.Parameters.AddWithValue("@Details", details);
                    command.ExecuteNonQuery();
                }
            }
        }

        #region 学校操作
        public List<School> GetAllSchools()
        {
            var schools = new List<School>();
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Schools", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            schools.Add(new School
                            {
                                SchoolId = Convert.ToInt32(reader["SchoolId"]),
                                Name = reader["Name"].ToString(),
                                Address = reader["Address"].ToString()
                            });
                        }
                    }
                }
            }
            return schools;
        }

        public School GetSchoolById(int id)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Schools WHERE SchoolId = @Id", connection))
                {
                    command.Parameters.AddWithValue("@Id", id);
                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            return new School
                            {
                                SchoolId = Convert.ToInt32(reader["SchoolId"]),
                                Name = reader["Name"].ToString(),
                                Address = reader["Address"].ToString()
                            };
                        }
                    }
                }
            }
            return null;
        }

        public int AddSchool(School school)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    INSERT INTO Schools (Name, Address)
                    VALUES (@Name, @Address);
                    SELECT last_insert_rowid();", connection))
                {
                    command.Parameters.AddWithValue("@Name", school.Name);
                    command.Parameters.AddWithValue("@Address", school.Address ?? (object)DBNull.Value);

                    int newId = Convert.ToInt32(command.ExecuteScalar());
                    LogOperation("添加学校", $"添加学校: {school.Name}");
                    return newId;
                }
            }
        }

        public bool UpdateSchool(School school)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    UPDATE Schools 
                    SET Name = @Name, Address = @Address
                    WHERE SchoolId = @SchoolId", connection))
                {
                    command.Parameters.AddWithValue("@SchoolId", school.SchoolId);
                    command.Parameters.AddWithValue("@Name", school.Name);
                    command.Parameters.AddWithValue("@Address", school.Address ?? (object)DBNull.Value);

                    int rowsAffected = command.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        LogOperation("更新学校", $"更新学校: {school.Name} (ID: {school.SchoolId})");
                        return true;
                    }
                    return false;
                }
            }
        }

        public bool DeleteSchool(int id)
        {
            var school = GetSchoolById(id);
            if (school == null) return false;

            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        // 删除学校下的所有学生
                        using (var command = new SQLiteCommand(@"
                            DELETE FROM Students WHERE ClassId IN 
                            (SELECT ClassId FROM Classes WHERE SchoolId = @SchoolId)", connection, transaction))
                        {
                            command.Parameters.AddWithValue("@SchoolId", id);
                            command.ExecuteNonQuery();
                        }

                        // 删除学校下的所有班级
                        using (var command = new SQLiteCommand("DELETE FROM Classes WHERE SchoolId = @SchoolId", connection, transaction))
                        {
                            command.Parameters.AddWithValue("@SchoolId", id);
                            command.ExecuteNonQuery();
                        }

                        // 删除学校
                        using (var command = new SQLiteCommand("DELETE FROM Schools WHERE SchoolId = @SchoolId", connection, transaction))
                        {
                            command.Parameters.AddWithValue("@SchoolId", id);
                            int rowsAffected = command.ExecuteNonQuery();

                            if (rowsAffected > 0)
                            {
                                transaction.Commit();
                                LogOperation("删除学校", $"删除学校: {school.Name} (ID: {id})");
                                return true;
                            }

                            transaction.Rollback();
                            return false;
                        }
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }
        #endregion

        #region 班级操作
        public List<Class> GetAllClasses()
        {
            var classes = new List<Class>();
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Classes", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            classes.Add(new Class
                            {
                                ClassId = Convert.ToInt32(reader["ClassId"]),
                                Name = reader["Name"].ToString(),
                                SchoolId = Convert.ToInt32(reader["SchoolId"])
                            });
                        }
                    }
                }
            }
            return classes;
        }

        public List<Class> GetClassesBySchoolId(int schoolId)
        {
            var classes = new List<Class>();
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Classes WHERE SchoolId = @SchoolId", connection))
                {
                    command.Parameters.AddWithValue("@SchoolId", schoolId);
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            classes.Add(new Class
                            {
                                ClassId = Convert.ToInt32(reader["ClassId"]),
                                Name = reader["Name"].ToString(),
                                SchoolId = Convert.ToInt32(reader["SchoolId"])
                            });
                        }
                    }
                }
            }
            return classes;
        }

        public Class GetClassById(int id)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Classes WHERE ClassId = @Id", connection))
                {
                    command.Parameters.AddWithValue("@Id", id);
                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            return new Class
                            {
                                ClassId = Convert.ToInt32(reader["ClassId"]),
                                Name = reader["Name"].ToString(),
                                SchoolId = Convert.ToInt32(reader["SchoolId"])
                            };
                        }
                    }
                }
            }
            return null;
        }

        public int AddClass(Class cls)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    INSERT INTO Classes (Name, SchoolId)
                    VALUES (@Name, @SchoolId);
                    SELECT last_insert_rowid();", connection))
                {
                    command.Parameters.AddWithValue("@Name", cls.Name);
                    command.Parameters.AddWithValue("@SchoolId", cls.SchoolId);

                    int newId = Convert.ToInt32(command.ExecuteScalar());
                    LogOperation("添加班级", $"添加班级: {cls.Name} (学校ID: {cls.SchoolId})");
                    return newId;
                }
            }
        }

        public bool UpdateClass(Class cls)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    UPDATE Classes 
                    SET Name = @Name, SchoolId = @SchoolId
                    WHERE ClassId = @ClassId", connection))
                {
                    command.Parameters.AddWithValue("@ClassId", cls.ClassId);
                    command.Parameters.AddWithValue("@Name", cls.Name);
                    command.Parameters.AddWithValue("@SchoolId", cls.SchoolId);

                    int rowsAffected = command.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        LogOperation("更新班级", $"更新班级: {cls.Name} (ID: {cls.ClassId})");
                        return true;
                    }
                    return false;
                }
            }
        }

        public bool DeleteClass(int id)
        {
            var cls = GetClassById(id);
            if (cls == null) return false;

            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        // 删除班级下的所有学生
                        using (var command = new SQLiteCommand("DELETE FROM Students WHERE ClassId = @ClassId", connection, transaction))
                        {
                            command.Parameters.AddWithValue("@ClassId", id);
                            command.ExecuteNonQuery();
                        }

                        // 删除班级
                        using (var command = new SQLiteCommand("DELETE FROM Classes WHERE ClassId = @ClassId", connection, transaction))
                        {
                            command.Parameters.AddWithValue("@ClassId", id);
                            int rowsAffected = command.ExecuteNonQuery();

                            if (rowsAffected > 0)
                            {
                                transaction.Commit();
                                LogOperation("删除班级", $"删除班级: {cls.Name} (ID: {id})");
                                return true;
                            }

                            transaction.Rollback();
                            return false;
                        }
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }
        #endregion

        #region 学生操作
        public List<Student> GetAllStudents()
        {
            var students = new List<Student>();
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Students", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            students.Add(new Student
                            {
                                StudentId = Convert.ToInt32(reader["StudentId"]),
                                Name = reader["Name"].ToString(),
                                Gender = reader["Gender"].ToString(),
                                BirthDate = reader["BirthDate"] != DBNull.Value ?
                                           DateTime.Parse(reader["BirthDate"].ToString()) : DateTime.MinValue,
                                ClassId = Convert.ToInt32(reader["ClassId"])
                            });
                        }
                    }
                }
            }
            return students;
        }

        public List<Student> GetStudentsByClassId(int classId)
        {
            var students = new List<Student>();
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Students WHERE ClassId = @ClassId", connection))
                {
                    command.Parameters.AddWithValue("@ClassId", classId);
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            students.Add(new Student
                            {
                                StudentId = Convert.ToInt32(reader["StudentId"]),
                                Name = reader["Name"].ToString(),
                                Gender = reader["Gender"].ToString(),
                                BirthDate = reader["BirthDate"] != DBNull.Value ?
                                           DateTime.Parse(reader["BirthDate"].ToString()) : DateTime.MinValue,
                                ClassId = Convert.ToInt32(reader["ClassId"])
                            });
                        }
                    }
                }
            }
            return students;
        }

        public Student GetStudentById(int id)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Students WHERE StudentId = @Id", connection))
                {
                    command.Parameters.AddWithValue("@Id", id);
                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            return new Student
                            {
                                StudentId = Convert.ToInt32(reader["StudentId"]),
                                Name = reader["Name"].ToString(),
                                Gender = reader["Gender"].ToString(),
                                BirthDate = reader["BirthDate"] != DBNull.Value ?
                                           DateTime.Parse(reader["BirthDate"].ToString()) : DateTime.MinValue,
                                ClassId = Convert.ToInt32(reader["ClassId"])
                            };
                        }
                    }
                }
            }
            return null;
        }

        public int AddStudent(Student student)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    INSERT INTO Students (Name, Gender, BirthDate, ClassId)
                    VALUES (@Name, @Gender, @BirthDate, @ClassId);
                    SELECT last_insert_rowid();", connection))
                {
                    command.Parameters.AddWithValue("@Name", student.Name);
                    command.Parameters.AddWithValue("@Gender", student.Gender ?? (object)DBNull.Value);
                    command.Parameters.AddWithValue("@BirthDate", student.BirthDate.ToString("yyyy-MM-dd"));
                    command.Parameters.AddWithValue("@ClassId", student.ClassId);

                    int newId = Convert.ToInt32(command.ExecuteScalar());
                    LogOperation("添加学生", $"添加学生: {student.Name} (班级ID: {student.ClassId})");
                    return newId;
                }
            }
        }

        public bool UpdateStudent(Student student)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    UPDATE Students 
                    SET Name = @Name, Gender = @Gender, BirthDate = @BirthDate, ClassId = @ClassId
                    WHERE StudentId = @StudentId", connection))
                {
                    command.Parameters.AddWithValue("@StudentId", student.StudentId);
                    command.Parameters.AddWithValue("@Name", student.Name);
                    command.Parameters.AddWithValue("@Gender", student.Gender ?? (object)DBNull.Value);
                    command.Parameters.AddWithValue("@BirthDate", student.BirthDate.ToString("yyyy-MM-dd"));
                    command.Parameters.AddWithValue("@ClassId", student.ClassId);

                    int rowsAffected = command.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        LogOperation("更新学生", $"更新学生信息: {student.Name} (ID: {student.StudentId})");
                        return true;
                    }
                    return false;
                }
            }
        }

        public bool DeleteStudent(int id)
        {
            var student = GetStudentById(id);
            if (student == null) return false;

            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("DELETE FROM Students WHERE StudentId = @StudentId", connection))
                {
                    command.Parameters.AddWithValue("@StudentId", id);
                    int rowsAffected = command.ExecuteNonQuery();

                    if (rowsAffected > 0)
                    {
                        LogOperation("删除学生", $"删除学生: {student.Name} (ID: {id})");
                        return true;
                    }
                    return false;
                }
            }
        }
        #endregion

        #region 日志操作
        public List<Log> GetAllLogs()
        {
            var logs = new List<Log>();
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand("SELECT * FROM Logs ORDER BY Timestamp DESC", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            logs.Add(new Log
                            {
                                LogId = Convert.ToInt32(reader["LogId"]),
                                Timestamp = DateTime.Parse(reader["Timestamp"].ToString()),
                                Operation = reader["Operation"].ToString(),
                                Details = reader["Details"].ToString()
                            });
                        }
                    }
                }
            }
            return logs;
        }

        public List<Log> SearchLogs(string searchTerm)
        {
            var logs = new List<Log>();
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(@"
                    SELECT * FROM Logs 
                    WHERE Operation LIKE @SearchTerm OR Details LIKE @SearchTerm
                    ORDER BY Timestamp DESC", connection))
                {
                    command.Parameters.AddWithValue("@SearchTerm", $"%{searchTerm}%");
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            logs.Add(new Log
                            {
                                LogId = Convert.ToInt32(reader["LogId"]),
                                Timestamp = DateTime.Parse(reader["Timestamp"].ToString()),
                                Operation = reader["Operation"].ToString(),
                                Details = reader["Details"].ToString()
                            });
                        }
                    }
                }
            }
            return logs;
        }
        #endregion
    }

    // 程序主类
    class Program
    {
        private static DatabaseManager _dbManager = new DatabaseManager();

        static void Main(string[] args)
        {
            Console.WriteLine("欢迎使用学生管理系统");
            _dbManager.LogOperation("系统", "系统启动");

            while (true)
            {
                Console.WriteLine("\n请选择操作:");
                Console.WriteLine("1. 学校管理");
                Console.WriteLine("2. 班级管理");
                Console.WriteLine("3. 学生管理");
                Console.WriteLine("4. 查看日志");
                Console.WriteLine("0. 退出系统");

                Console.Write("请输入您的选择: ");
                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        ManageSchools();
                        break;
                    case "2":
                        ManageClasses();
                        break;
                    case "3":
                        ManageStudents();
                        break;
                    case "4":
                        ViewLogs();
                        break;
                    case "0":
                        _dbManager.LogOperation("系统", "系统关闭");
                        Console.WriteLine("感谢使用，再见！");
                        return;
                    default:
                        Console.WriteLine("无效的选择，请重试。");
                        break;
                }
            }
        }

        #region 学校管理
        private static void ManageSchools()
        {
            while (true)
            {
                Console.WriteLine("\n学校管理:");
                Console.WriteLine("1. 查看所有学校");
                Console.WriteLine("2. 添加学校");
                Console.WriteLine("3. 更新学校");
                Console.WriteLine("4. 删除学校");
                Console.WriteLine("0. 返回主菜单");

                Console.Write("请输入您的选择: ");
                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        DisplayAllSchools();
                        break;
                    case "2":
                        AddSchool();
                        break;
                    case "3":
                        UpdateSchool();
                        break;
                    case "4":
                        DeleteSchool();
                        break;
                    case "0":
                        return;
                    default:
                        Console.WriteLine("无效的选择，请重试。");
                        break;
                }
            }
        }

        private static void DisplayAllSchools()
        {
            var schools = _dbManager.GetAllSchools();
            if (schools.Count == 0)
            {
                Console.WriteLine("暂无学校记录！");
                return;
            }

            Console.WriteLine("\n所有学校:");
            foreach (var school in schools)
            {
                Console.WriteLine(school);
            }
        }

        private static void AddSchool()
        {
            Console.WriteLine("\n添加新学校:");

            Console.Write("学校名称: ");
            string name = Console.ReadLine();

            Console.Write("学校地址: ");
            string address = Console.ReadLine();

            var school = new School { Name = name, Address = address };
            int newId = _dbManager.AddSchool(school);

            Console.WriteLine($"学校添加成功，ID: {newId}");
        }

        private static void UpdateSchool()
        {
            DisplayAllSchools();

            Console.Write("\n请输入要更新的学校ID: ");
            if (!int.TryParse(Console.ReadLine(), out int schoolId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            var school = _dbManager.GetSchoolById(schoolId);
            if (school == null)
            {
                Console.WriteLine("未找到该学校！");
                return;
            }

            Console.WriteLine($"正在更新学校: {school.Name}");

            Console.Write("新学校名称 (按回车保持不变): ");
            string name = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(name))
                school.Name = name;

            Console.Write("新学校地址 (按回车保持不变): ");
            string address = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(address))
                school.Address = address;

            bool success = _dbManager.UpdateSchool(school);
            if (success)
                Console.WriteLine("学校更新成功！");
            else
                Console.WriteLine("学校更新失败！");
        }

        private static void DeleteSchool()
        {
            DisplayAllSchools();

            Console.Write("\n请输入要删除的学校ID: ");
            if (!int.TryParse(Console.ReadLine(), out int schoolId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            Console.Write($"确定要删除ID为 {schoolId} 的学校吗? 此操作将删除该学校下的所有班级和学生！(Y/N): ");
            string confirm = Console.ReadLine();

            if (confirm.Equals("Y", StringComparison.OrdinalIgnoreCase))
            {
                bool success = _dbManager.DeleteSchool(schoolId);
                if (success)
                    Console.WriteLine("学校删除成功！");
                else
                    Console.WriteLine("学校删除失败，可能不存在该ID！");
            }
        }
        #endregion

        #region 班级管理
        private static void ManageClasses()
        {
            while (true)
            {
                Console.WriteLine("\n班级管理:");
                Console.WriteLine("1. 查看所有班级");
                Console.WriteLine("2. 查看指定学校的班级");
                Console.WriteLine("3. 添加班级");
                Console.WriteLine("4. 更新班级");
                Console.WriteLine("5. 删除班级");
                Console.WriteLine("0. 返回主菜单");

                Console.Write("请输入您的选择: ");
                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        DisplayAllClasses();
                        break;
                    case "2":
                        DisplayClassesBySchool();
                        break;
                    case "3":
                        AddClass();
                        break;
                    case "4":
                        UpdateClass();
                        break;
                    case "5":
                        DeleteClass();
                        break;
                    case "0":
                        return;
                    default:
                        Console.WriteLine("无效的选择，请重试。");
                        break;
                }
            }
        }

        private static void DisplayAllClasses()
        {
            var classes = _dbManager.GetAllClasses();
            if (classes.Count == 0)
            {
                Console.WriteLine("暂无班级记录！");
                return;
            }

            Console.WriteLine("\n所有班级:");
            foreach (var cls in classes)
            {
                Console.WriteLine(cls);
            }
        }

        private static void DisplayClassesBySchool()
        {
            DisplayAllSchools();

            Console.Write("\n请输入学校ID: ");
            if (!int.TryParse(Console.ReadLine(), out int schoolId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            var classes = _dbManager.GetClassesBySchoolId(schoolId);
            if (classes.Count == 0)
            {
                Console.WriteLine("该学校暂无班级记录！");
                return;
            }

            Console.WriteLine($"\n学校ID: {schoolId} 下的所有班级:");
            foreach (var cls in classes)
            {
                Console.WriteLine(cls);
            }
        }

        private static void AddClass()
        {
            DisplayAllSchools();

            Console.WriteLine("\n添加新班级:");

            Console.Write("所属学校ID: ");
            if (!int.TryParse(Console.ReadLine(), out int schoolId))
            {
                Console.WriteLine("无效的学校ID！");
                return;
            }

            // 验证学校是否存在
            var school = _dbManager.GetSchoolById(schoolId);
            if (school == null)
            {
                Console.WriteLine("该学校不存在！");
                return;
            }

            Console.Write("班级名称: ");
            string name = Console.ReadLine();

            var cls = new Class { Name = name, SchoolId = schoolId };
            int newId = _dbManager.AddClass(cls);

            Console.WriteLine($"班级添加成功，ID: {newId}");
        }

        private static void UpdateClass()
        {
            DisplayAllClasses();

            Console.Write("\n请输入要更新的班级ID: ");
            if (!int.TryParse(Console.ReadLine(), out int classId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            var cls = _dbManager.GetClassById(classId);
            if (cls == null)
            {
                Console.WriteLine("未找到该班级！");
                return;
            }

            Console.WriteLine($"正在更新班级: {cls.Name} (学校ID: {cls.SchoolId})");

            Console.Write("新班级名称 (按回车保持不变): ");
            string name = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(name))
                cls.Name = name;

            Console.Write("新所属学校ID (按回车保持不变): ");
            string schoolIdStr = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(schoolIdStr) && int.TryParse(schoolIdStr, out int schoolId))
            {
                // 验证学校是否存在
                var school = _dbManager.GetSchoolById(schoolId);
                if (school == null)
                {
                    Console.WriteLine("该学校不存在！更新取消");
                    return;
                }
                cls.SchoolId = schoolId;
            }

            bool success = _dbManager.UpdateClass(cls);
            if (success)
                Console.WriteLine("班级更新成功！");
            else
                Console.WriteLine("班级更新失败！");
        }

        private static void DeleteClass()
        {
            DisplayAllClasses();

            Console.Write("\n请输入要删除的班级ID: ");
            if (!int.TryParse(Console.ReadLine(), out int classId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            Console.Write($"确定要删除ID为 {classId} 的班级吗? 此操作将删除该班级下的所有学生！(Y/N): ");
            string confirm = Console.ReadLine();

            if (confirm.Equals("Y", StringComparison.OrdinalIgnoreCase))
            {
                bool success = _dbManager.DeleteClass(classId);
                if (success)
                    Console.WriteLine("班级删除成功！");
                else
                    Console.WriteLine("班级删除失败，可能不存在该ID！");
            }
        }
        #endregion

        #region 学生管理
        private static void ManageStudents()
        {
            while (true)
            {
                Console.WriteLine("\n学生管理:");
                Console.WriteLine("1. 查看所有学生");
                Console.WriteLine("2. 查看指定班级的学生");
                Console.WriteLine("3. 添加学生");
                Console.WriteLine("4. 更新学生");
                Console.WriteLine("5. 删除学生");
                Console.WriteLine("0. 返回主菜单");

                Console.Write("请输入您的选择: ");
                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        DisplayAllStudents();
                        break;
                    case "2":
                        DisplayStudentsByClass();
                        break;
                    case "3":
                        AddStudent();
                        break;
                    case "4":
                        UpdateStudent();
                        break;
                    case "5":
                        DeleteStudent();
                        break;
                    case "0":
                        return;
                    default:
                        Console.WriteLine("无效的选择，请重试。");
                        break;
                }
            }
        }

        private static void DisplayAllStudents()
        {
            var students = _dbManager.GetAllStudents();
            if (students.Count == 0)
            {
                Console.WriteLine("暂无学生记录！");
                return;
            }

            Console.WriteLine("\n所有学生:");
            foreach (var student in students)
            {
                Console.WriteLine(student);
            }
        }

        private static void DisplayStudentsByClass()
        {
            DisplayAllClasses();

            Console.Write("\n请输入班级ID: ");
            if (!int.TryParse(Console.ReadLine(), out int classId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            var students = _dbManager.GetStudentsByClassId(classId);
            if (students.Count == 0)
            {
                Console.WriteLine("该班级暂无学生记录！");
                return;
            }

            Console.WriteLine($"\n班级ID: {classId} 下的所有学生:");
            foreach (var student in students)
            {
                Console.WriteLine(student);
            }
        }

        private static void AddStudent()
        {
            DisplayAllClasses();

            Console.WriteLine("\n添加新学生:");

            Console.Write("所属班级ID: ");
            if (!int.TryParse(Console.ReadLine(), out int classId))
            {
                Console.WriteLine("无效的班级ID！");
                return;
            }

            // 验证班级是否存在
            var cls = _dbManager.GetClassById(classId);
            if (cls == null)
            {
                Console.WriteLine("该班级不存在！");
                return;
            }

            Console.Write("学生姓名: ");
            string name = Console.ReadLine();

            Console.Write("学生性别: ");
            string gender = Console.ReadLine();

            DateTime birthDate;
            Console.Write("出生日期 (格式: yyyy-MM-dd): ");
            if (!DateTime.TryParse(Console.ReadLine(), out birthDate))
            {
                birthDate = DateTime.MinValue;
                Console.WriteLine("日期格式无效，将使用默认值。");
            }

            var student = new Student
            {
                Name = name,
                Gender = gender,
                BirthDate = birthDate,
                ClassId = classId
            };

            int newId = _dbManager.AddStudent(student);
            Console.WriteLine($"学生添加成功，ID: {newId}");
        }

        private static void UpdateStudent()
        {
            DisplayAllStudents();

            Console.Write("\n请输入要更新的学生ID: ");
            if (!int.TryParse(Console.ReadLine(), out int studentId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            var student = _dbManager.GetStudentById(studentId);
            if (student == null)
            {
                Console.WriteLine("未找到该学生！");
                return;
            }

            Console.WriteLine($"正在更新学生: {student.Name} (ID: {student.StudentId})");

            Console.Write("新学生姓名 (按回车保持不变): ");
            string name = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(name))
                student.Name = name;

            Console.Write("新学生性别 (按回车保持不变): ");
            string gender = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(gender))
                student.Gender = gender;

            Console.Write("新出生日期 (格式: yyyy-MM-dd, 按回车保持不变): ");
            string birthDateStr = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(birthDateStr))
            {
                if (DateTime.TryParse(birthDateStr, out DateTime birthDate))
                    student.BirthDate = birthDate;
                else
                    Console.WriteLine("日期格式无效，将保持原值。");
            }

            Console.Write("新所属班级ID (按回车保持不变): ");
            string classIdStr = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(classIdStr) && int.TryParse(classIdStr, out int classId))
            {
                // 验证班级是否存在
                var cls = _dbManager.GetClassById(classId);
                if (cls == null)
                {
                    Console.WriteLine("该班级不存在！更新取消");
                    return;
                }
                student.ClassId = classId;
            }

            bool success = _dbManager.UpdateStudent(student);
            if (success)
                Console.WriteLine("学生更新成功！");
            else
                Console.WriteLine("学生更新失败！");
        }

        private static void DeleteStudent()
        {
            DisplayAllStudents();

            Console.Write("\n请输入要删除的学生ID: ");
            if (!int.TryParse(Console.ReadLine(), out int studentId))
            {
                Console.WriteLine("无效的ID！");
                return;
            }

            Console.Write($"确定要删除ID为 {studentId} 的学生吗? (Y/N): ");
            string confirm = Console.ReadLine();

            if (confirm.Equals("Y", StringComparison.OrdinalIgnoreCase))
            {
                bool success = _dbManager.DeleteStudent(studentId);
                if (success)
                    Console.WriteLine("学生删除成功！");
                else
                    Console.WriteLine("学生删除失败，可能不存在该ID！");
            }
        }
        #endregion

        #region 日志管理
        private static void ViewLogs()
        {
            while (true)
            {
                Console.WriteLine("\n日志查看:");
                Console.WriteLine("1. 查看所有日志");
                Console.WriteLine("2. 搜索日志");
                Console.WriteLine("0. 返回主菜单");

                Console.Write("请输入您的选择: ");
                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        DisplayAllLogs();
                        break;
                    case "2":
                        SearchLogs();
                        break;
                    case "0":
                        return;
                    default:
                        Console.WriteLine("无效的选择，请重试。");
                        break;
                }
            }
        }

        private static void DisplayAllLogs()
        {
            var logs = _dbManager.GetAllLogs();
            if (logs.Count == 0)
            {
                Console.WriteLine("暂无日志记录！");
                return;
            }

            Console.WriteLine("\n所有日志记录:");
            foreach (var log in logs)
            {
                Console.WriteLine(log);
            }

            // 如果日志太多，添加分页功能
            if (logs.Count > 20)
            {
                Console.WriteLine("\n显示了前20条记录。按任意键继续...");
                Console.ReadKey();
            }
        }

        private static void SearchLogs()
        {
            Console.Write("\n请输入搜索关键词: ");
            string searchTerm = Console.ReadLine();

            var logs = _dbManager.SearchLogs(searchTerm);
            if (logs.Count == 0)
            {
                Console.WriteLine("未找到匹配的日志记录！");
                return;
            }

            Console.WriteLine($"\n找到 {logs.Count} 条匹配的日志记录:");
            foreach (var log in logs)
            {
                Console.WriteLine(log);
            }

            if (logs.Count > 20)
            {
                Console.WriteLine("\n显示了前20条记录。按任意键继续...");
                Console.ReadKey();
            }
        }
        #endregion
    }
}